import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Button, Input, message, Icon, Form, Select, AutoComplete } from 'antd';
import { routerRedux } from 'dva/router';
import styles from './index.less';

const EditModal = React.lazy(() => import('./editModal'));
const FieldTable = React.lazy(() => import('./fieldTable'));
const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
let responseFieldArr = [];
let requestFieldArr = [];
const formItemLayout = {
  labelCol: {
    xs: { span: 2 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};
@connect(({ customApi, loading }) => ({
  customApi,
  loading: loading.effects['customApi/fetchApiDetailById'],
}))
class CustomApi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      requestField: [],
      responseField: [],
      fieldType: null,
      apiId: null,
      name: null,
      url: null,
      errorMessage: null,
      method: 'POST',
      isUsed: false,
      fieldObj: {},
    };
    this.requestFieldColumns = [
      {
        key: 'name',
        align: 'left',
        title: '字段业务名',
        dataIndex: 'name',
        width: 'calc(30vw)',
      },
      {
        key: 'id',
        align: 'left',
        title: '字段名',
        dataIndex: 'id',
        width: 'calc(30vw)',
      },
      {
        key: 'fieldType',
        align: 'left',
        title: '类型',
        dataIndex: 'fieldType',
        width: 'calc(20vw)',
      },
      {
        key: 'value',
        align: 'left',
        title: '默认值',
        dataIndex: 'value',
        width: 'calc(20vw)',
      },
      {
        title: '操作',
        align: 'left',
        width: 'calc(30vw)',
        render: (text, row) => {
          return (
            <div>
              <Button
                htmlType="button"
                size="small"
                type="primary"
                icon="edit"
                className={styles.processBtn}
                onClick={() => this.editFieldById(row, 'requestField')}
              >
                <FormattedMessage id="app.processTemplate.btn-edit" />
              </Button>
              <Button
                type="danger"
                htmlType="button"
                size="small"
                icon="delete"
                className={styles.processBtn}
                onClick={() => this.delFieldById(row, 'requestField')}
              >
                <FormattedMessage id="app.processTemplate.btn-del" />
              </Button>
            </div>
          );
        },
      },
    ];
    this.responseFieldColumns = [
      {
        key: 'name',
        align: 'left',
        title: '字段业务名',
        dataIndex: 'name',
        width: 'calc(30vw)',
      },
      {
        key: 'id',
        align: 'left',
        title: '字段名',
        dataIndex: 'id',
        width: 'calc(30vw)',
      },
      {
        key: 'fieldType',
        align: 'left',
        title: '类型',
        dataIndex: 'fieldType',
        width: 'calc(30vw)',
      },
      {
        title: '操作',
        align: 'left',
        width: 'calc(30vw)',
        render: (text, row) => {
          return (
            <div>
              <Button
                htmlType="button"
                size="small"
                type="primary"
                icon="edit"
                className={styles.processBtn}
                onClick={() => this.editFieldById(row, 'responseField')}
              >
                <FormattedMessage id="app.processTemplate.btn-edit" />
              </Button>
              <Button
                type="danger"
                htmlType="button"
                size="small"
                icon="delete"
                className={styles.processBtn}
                onClick={() => this.delFieldById(row, 'responseField')}
              >
                <FormattedMessage id="app.processTemplate.btn-del" />
              </Button>
            </div>
          );
        },
      },
    ];
  }

  componentDidMount() {
    if (this.props.location.state.apiId) {
      this.setState(
        {
          apiId: this.props.location.state.apiId,
        },
        () => {
          this.fetchApiDetailById(this.state.apiId);
        }
      );
    }
    requestFieldArr = [];
    responseFieldArr = [];
  }

  componentWillUnmount() {
    this.props.form.resetFields();
  }

  saveApi = e => {
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let requestField = this.setFieldsData(this.state.requestField);
        let responseField = this.setFieldsData(this.state.responseField);
        let url = 'customApi/add'
        let obj = {
          name:values.name,
          url:values.url,
          method:values.method,
          errorMessage:values.errorMessage,
          requestFields:requestField,
          responseFields:responseField,
        }
        if(this.state.apiId){
          obj.id = this.state.apiId;
          url = 'customApi/edit'
        }
        dispatch({
          type: url,
          payload: obj,
          callback: res => {
            if (res.apiId) {
              obj['apiId'] = res.apiId;
              this.setState(
                {
                  apiId: res.apiId,
                },
                () => {
                  this.fetchApiDetailById(res.apiId);
                  message.info('保存成功');
                }
              );
            }
          },
        });
      } else {

      }
    });
  };

  setFieldsData = data => {
    for(let item of data){
      if(item.children && item.children.length > 0){
        let fieldName = item.id;
        let fieldNameZh = item.name;
        item.name = fieldName;
        item.nameZh = fieldNameZh;
        this.setFieldsData(item.children);
      }else {
        let fieldName = item.id;
        let fieldNameZh = item.name;
        item.name = fieldName;
        item.nameZh = fieldNameZh;
      }
    }
    return data;
  }

  pushRequestField = (val, type, method) => {

    // if(!this.ArrayDetection(val)){
    //   return message.error('该字段名已存在，请替换再试')
    // }
    if (type === 'requestField') {
      if (method === 'edit') {
        this.dataFix(val);
      }
      requestFieldArr.push(val);
      this.setState(
        {
          requestField: requestFieldArr,
        },
        () => {

        }
      );
    } else {
      if (method === 'edit') {
        this.dataFix(val);
      }
      responseFieldArr.push(val);
      this.setState(
        {
          responseField: responseFieldArr,
        },
        () => {

        }
      );
    }
  };

  addField(type) {
    this.setState(
      {
        fieldType: type,
      },
      () => {

        this.EditModal.showModal(type);
      }
    );
  }

  checkUrl(rule, value, callback) {
    try {
      throw new Error(rule.field + '不能为空');
    } catch (err) {
      callback(err);
    }
  }

  dataFix(row) {
    const that = this;
    let type = row.type;
    let arr = that.state[type];
    arr.splice(
      arr.findIndex(v => v.id === row.id),
      1
    );
  }

  ArrayDetection(row) {
    const that = this;
    let type = row.type;
    let arr = that.state[type];
    let result = arr.find(item => {
      return item.id == row.id;
    });
    return !result;
  }

  delFieldById(row, requestMethod) {
    const that = this;
    let type = requestMethod;
    let arr = that.state[type];
    arr.splice(
      arr.findIndex(v => v.id === row.id),
      1
    );
    that.setState(
      {
        [type]: arr,
      },
      () => {

      }
    );
  }

  editFieldById(row, requestMethod) {
    const that = this;
    let type = requestMethod;

    this.setState(
      {
        fieldType: type,
      },
      () => {
        this.EditModal.showModal(type, row, 'edit');
      }
    );
  }

  fetchApiDetailById(id) {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/fetchApiDetailById',
        payload: { id: id },
        callback: res => {

          requestFieldArr = this.reverseFieldsData(res.requestFields);
          responseFieldArr = this.reverseFieldsData(res.responseFields);
          console.log(requestFieldArr);
          this.setState(
            {
              name: res.name,
              url: res.url,
              method: res.method,
              isUsed: res.isUsed,
              errorMessage: res.errorMessage,
              requestField: requestFieldArr,
              responseField: responseFieldArr,
              fieldObj: res,
            });
        },
      });
    });
  }

  reverseFieldsData = data => {
    for(let item of data){
      if(item.children && item.children.length > 0){
        item.name = item.nameZh;
        this.reverseFieldsData(item.children);
      }else {
        item.name = item.nameZh;
      }
    }
    return data;
  }

  testApi(obj) {
    const { dispatch } = this.props;

    if (JSON.stringify(obj) === '{}') {
      return message.error('请先保存后，再开始测试');
    }
    this.reqRef = requestAnimationFrame(() => {
      console.log(obj);
      dispatch({
        type: 'customApi/test',
        payload: { api: JSON.stringify(obj) },
      });
    });
  }

  backList() {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/knowledgeDesign/customApi'));
  }

  checkField(rule, value, callback) {

    if (value != null) {
      callback();
    } else {
      callback(rule.field + '不能为空');
    }
  }

  checkFieldByUrl = (rule, value, callback) => {
    const reg = /(http):\/\/([\w.]+\/?)\S*/;
    if (rule.field === 'url') {
      if (value) {
        if (!reg.test(value)) {
          callback('请求地址以HTTP开头');
        }
      } else {
        callback('请求地址以HTTP开头');
      }
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { isUsed } = this.state;
    // @ts-ignore
    // @ts-ignore
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Row className={styles.colorBackground}>
            <Col style={{ padding: 10 }} xs={5}>
              <div className={styles.title}>
                <FormattedMessage id="app.customApi.title-edit" />
              </div>
            </Col>

            <div
              style={{
                float: 'right',
                paddingTop: 16,
                paddingRight: 20,
                color: 'rgb(21,144,255)',
                cursor: 'pointer',
              }}
              onClick={() => this.backList()}
            >
              <Icon type="bars" style={{ marginRight: 5 }} />
              <FormattedMessage id="app.customApi.backList" />
            </div>
          </Row>
          <Card bordered={false}>
            <Form {...formItemLayout} onSubmit={this.saveApi}>
              <Form.Item label={<FormattedMessage id="app.customApi.apiName" />} hasFeedback>
                {getFieldDecorator('name', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    {
                      required: true,
                      message: '接口名称不可为空',
                    },
                    {
                      validator: '',
                    },
                  ],
                  initialValue: this.state.name,
                })(<Input placeholder="请输入接口名称" />)}
              </Form.Item>
              <Form.Item label={<FormattedMessage id="app.customApi.requestMethod" />} hasFeedback>
                {getFieldDecorator('method', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    {
                      required: true,
                      message: '请选择接口请求方式',
                    },
                    {
                      validator: '',
                    },
                  ],
                  initialValue: this.state.method,
                })(
                  <Select>
                    <Option value="GET">GET</Option>
                    <Option value="POST">POST</Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item label={<FormattedMessage id="app.customApi.requestAddress" />}>
                {getFieldDecorator('url', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    {
                      required: true,
                      message: '请输入请求地址不可为空',
                      whitespace: true,
                    },
                    {
                      validator: '',
                    },
                  ],
                  initialValue: this.state.url,
                })(<Input placeholder="请输入请求地址，以HTTP开头" />)}
              </Form.Item>
              <Form.Item label={<FormattedMessage id="app.customApi.requestField" />}>
                {
                  <Button
                    type="dashed"
                    htmlType="button"
                    icon="plus"
                    style={{
                      marginLeft: 10,
                      marginRight: 5,
                      backgroundColor: 'skyblue',
                      color: '#fff',
                    }}
                    onClick={() => this.addField('requestField')}
                  >
                    <FormattedMessage id="app.customApi.add" />
                  </Button>
                }
              </Form.Item>
              <Form.Item>
                <FieldTable data={this.state.requestField} columns={this.requestFieldColumns} />
              </Form.Item>
              <Form.Item label={<FormattedMessage id="app.customApi.responseField" />}>
                {
                  <Button
                    type="dashed"
                    htmlType="button"
                    icon="plus"
                    style={{
                      marginLeft: 10,
                      marginRight: 5,
                      backgroundColor: 'orange',
                      color: '#fff',
                    }}
                    onClick={() => this.addField('responseField')}
                  >
                    <FormattedMessage id="app.customApi.add" />
                  </Button>
                }
              </Form.Item>
              <Form.Item>
                <FieldTable data={this.state.responseField} columns={this.responseFieldColumns} />
              </Form.Item>
              <Form.Item
                label={<FormattedMessage id="app.customApi.Call-Failed-the-art-of-speaking" />}
                hasFeedback
              >
                {getFieldDecorator('errorMessage', {
                  validateTrigger: ['onChange', 'onBlur'],
                  rules: [
                    {
                      required: true,
                      message: '请输入调用失败话术',
                    },
                    {
                      validator: '',
                    },
                  ],
                  initialValue: this.state.errorMessage,
                })(<Input placeholder="请输入调用失败话术" />)}
              </Form.Item>
              <Form.Item>
                <Button
                  htmlType="button"
                  style={{ marginLeft: 143 }}
                  onClick={() => {
                    this.testApi(this.state.fieldObj);
                  }}
                >
                  <FormattedMessage id="app.customApi.apiTest" />
                </Button>
                {
                  <Button type="primary" htmlType="submit" style={{ marginLeft: 10 }}>
                    <FormattedMessage id="app.customApi.apiSave" />
                  </Button>
                }
              </Form.Item>
            </Form>
            <EditModal
              wrappedComponentRef={e => (this.EditModal = e)}
              addRequestFieldFun={this.pushRequestField}
            />
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(CustomApi));
